package org.kfive.nova.io.nio;

import java.awt.geom.PathIterator;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.Pipe;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Random;

/*
* PipeTest.java
* Created  by  lizhanwu
* Created on 2016-5-19 17:09
*/
public class PipeTest {

    public static void main(String[] args) {
        WritableByteChannel out = Channels.newChannel(System.out);
        Pipe pipe = null;

        ReadableByteChannel workerChannel = null;
        ByteBuffer data = ByteBuffer.allocate(100);
        try {
            pipe = Pipe.open();
            Worker worker = new Worker(pipe.sink(),10);
            worker.start();
            workerChannel = pipe.source();
            while (workerChannel.read(data)>=0){
                System.out.println("reading......");
                data.flip();
                out.write(data);
                data.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static class Worker extends Thread{

        WritableByteChannel channel;

        private int reps;

        private String[] products = {"1111","2222","3333","4444"};

        private Random random = new Random();

        Worker(WritableByteChannel channel,int reps){
            this.channel = channel;
            this.reps = reps;
        }

        public void run(){

            ByteBuffer buffer = ByteBuffer.allocate(100);
            try {
                for (int i=0;i<reps;i++){
                    buffer.clear();
                    buffer.put(products[random.nextInt(products.length)].getBytes());
                    buffer.put("\r\n".getBytes());
                    buffer.flip();
                    while (this.channel.write(buffer)>0){
                        System.out.println("writing......");
                    }
                }
                this.channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }
}
